package com.suyafei.controller;


import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.suyafei.enums.BizCodeEnum;
import com.suyafei.enums.ClientTypeEnum;
import com.suyafei.enums.ProductOrderPayTypeEnum;
import com.suyafei.request.ConfirmOrderRequest;
import com.suyafei.service.ProductOrderService;
import com.suyafei.util.JsonData;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author suyafei
 * @since 2021-03-15
 */
@RestController
@RequestMapping("/api/order/v1")
@Slf4j
public class ProductOrderController {

    @Autowired
    private ProductOrderService productOrderService;


    @ApiOperation("提交订单")
    @PostMapping("confirm")
    public JsonData confirmOrder(
            @ApiParam("订单对象")
            @RequestBody ConfirmOrderRequest confirmOrderRequest,
            @ApiParam("请求对象")
                    HttpServletResponse response) {
        JsonData jsonData = productOrderService.confirmOrder(confirmOrderRequest);
        if (jsonData.getCode()==0) {


            String clientType = confirmOrderRequest.getClientType();
            String payType = confirmOrderRequest.getPayType();

            //如果是支付宝网页支付，都是跳转网页，APP除外
            if (payType.equalsIgnoreCase(ProductOrderPayTypeEnum.ALIPAY.name())) {
                log.info("创建支付宝订单成功{}",confirmOrderRequest.toString());

                if (clientType.equalsIgnoreCase(ClientTypeEnum.H5.name())) {
                    writeData(response,jsonData);
                } else if (clientType.equalsIgnoreCase(ClientTypeEnum.APP.name())) {
                    // APP SDK支付 TODO
                }
            } else if (payType.equalsIgnoreCase(ProductOrderPayTypeEnum.WECHAT.name())) {
                //微信支付 TODO
            }
        }else{


            log.error("创建订单失败{}", jsonData.toString());
        }
        return jsonData;

    }

    /**
     * 查询订单状态
     * @param outTradeNo
     * @return
     */
    @ApiOperation("RPC-查询订单状态")
    @GetMapping("out_trade_no")
    public JsonData queryProductOrderState(@RequestParam("out_trade_no") String outTradeNo){
        String state = productOrderService.queryProductOrder(outTradeNo);
        return StringUtils.isBlank(state) ? JsonData.buildResult(BizCodeEnum.ORDER_CONFIRM_NOT_EXIST) : JsonData.buildSuccess(state);
   }


    private void writeData(HttpServletResponse response, JsonData jsonData) {
        try {
            response.setContentType("text/html;charset=UTF8);");
            response.getWriter().write(jsonData.getData().toString());
            response.getWriter().flush();
            response.getWriter().close();
        } catch (Exception e) {

            log.error("写出Html异常{}",e);
        }
        }
}

